package com.crm.controller;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.crm.entity.Message;
import com.crm.service.MessageService;
import com.crm.util.Result;

//消息控制层
@RestController
@RequestMapping("/message")
public class MessageController {
	@Autowired
	private MessageService messageService;

	/**
	 * 消息的添加
	 * 
	 * @param message
	 * @return
	 */
	@RequestMapping("/add")
	public Object add(Message message) {
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 设置日期格式
		message.setSentTime(df.format(new Date()));// 发送时间
		message.setState("未读");
		message.setIsDel("否");
		Result result = new Result("0", "true", messageService.add(message), "success");
		return result;
	}
	/**
	 * 修改状态和读取时间 
	 * 
	 * @param message
	 * @return
	 */
	@RequestMapping("/update")
	public Object update(Message message) {
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 设置日期格式
		message.setReadTime(df.format(new Date()));// 读取时间
		message.setState("已读");
		Result result = new Result("0", "true", messageService.update(message), "success");
		return result;
	}

	/**
	 * 根据登录名去查询未读的消息
	 * 
	 * @param askerName
	 * @return
	 */
	@RequestMapping("/noRead")
	public Object noRead(String askerName) {
//		判断是否存在未读的消息==null
		if (messageService.noReadCount(askerName) != 0) {
			Result result = new Result("0", "true", messageService.noReadCount(askerName),
					messageService.noRead(askerName));
			return result;
		}
		Result result = new Result("0", "true", 0, "没有未读消息");
		return result;
	}

	/**
	 * 根据登录名去查询未读的消息
	 * 
	 * @param askerName
	 * @return
	 */
	@RequestMapping("/getAll")
	public Object getAll(@RequestParam Map<String, Object> map, @RequestParam int page, @RequestParam int limit,
			String askerName) {
		map.put("page", (page - 1) * limit);
		map.put("limit", limit);
		map.put("askerName", askerName);
		Result result = new Result("0", "true", messageService.getAllCount(map), messageService.getAll(map));
		return result;
	}
}
